package com.iotproject.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.iotproject.eduservice.entity.EduSubject;
import com.iotproject.eduservice.entity.excel.SubjectData;
import com.iotproject.eduservice.entity.subject.OneSubject;
import com.iotproject.eduservice.entity.subject.TwoSubject;
import com.iotproject.eduservice.listener.SubjectExcelListener;
import com.iotproject.eduservice.mapper.EduSubjectMapper;
import com.iotproject.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-11-07
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void importSubjectData(MultipartFile file, EduSubjectService subjectService) {
        try {
            //读取Excel 表数据
            InputStream fileStream = file.getInputStream();
            EasyExcel.read(fileStream, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //获取所有科目，以树形结构显示
    @Override
    public List<OneSubject> getAllSubject() {
        //查询一级列表
        QueryWrapper<EduSubject> oneSubjectQueryWrapper = new QueryWrapper<>();
        oneSubjectQueryWrapper.eq("parent_id", 0);
        List<EduSubject> oneSubjects = baseMapper.selectList(oneSubjectQueryWrapper);
        //查询二级列表
        QueryWrapper<EduSubject> twoSubjectQueryWrapper = new QueryWrapper<>();
        twoSubjectQueryWrapper.ne("parent_id", 0);
        List<EduSubject> twoSubjects = baseMapper.selectList(twoSubjectQueryWrapper);
        //封装一级列表
        List<OneSubject> res = new ArrayList<>();

        for (int i = 0; i < oneSubjects.size(); i++) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(oneSubjects.get(i), oneSubject);
            //封装二级列表
            List<TwoSubject> children = new ArrayList<>();
            for (int m = 0; m < twoSubjects.size(); m++) {
                //如果二级列表的parent_id == 一级列表的id，说明这个二级列表属于一级列表
                if (twoSubjects.get(m).getParentId().equals(oneSubjects.get(i).getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(twoSubjects.get(m), twoSubject);
                    children.add(twoSubject);
                }
            }
            //将二级列表添加到一级列表
            oneSubject.setChildren(children);
            //将完整的一级列表添加到结果列表
            res.add(oneSubject);
        }
        return res;
    }
}
